﻿using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using TimKiem.DTO.TimKiem;
using TimKiem.DataLayer.TimKiem;
using System.Collections.Generic;

namespace TKDVQ10.Keyword
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class KeywordHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";

            var start = 0;
            var limit = 10;
            var sort = string.Empty;
            var dir = string.Empty;
            var query = string.Empty;

            if (!string.IsNullOrEmpty(context.Request["start"]))
            {
                start = int.Parse(context.Request["start"]);
            }

            if (!string.IsNullOrEmpty(context.Request["limit"]))
            {
                limit = int.Parse(context.Request["limit"]);
            }

            if (!string.IsNullOrEmpty(context.Request["sort"]))
            {
                sort = context.Request["sort"];
            }

            if (!string.IsNullOrEmpty(context.Request["dir"]))
            {
                dir = context.Request["dir"];
            }

            if (!string.IsNullOrEmpty(context.Request["query"]))
            {
                query = context.Request["query"];
            }

            Ext.Net.Paging<TuKhoaDTO> keywords = GetCompletionList(start, limit, sort, dir, query);

            context.Response.Write(string.Format("{{total:{1},'keywords':{0}}}", Ext.Net.JSON.Serialize(keywords.Data), keywords.TotalRecords));
        }

        public static Ext.Net.Paging<TuKhoaDTO> GetCompletionList(int start, int limit, string sort, string dir, string filter)
        {
            DataSet ds=TimKiemRepository.GetAllKeyword();
            List<TuKhoaDTO> keywords=new List<TuKhoaDTO>();
            if(ds!=null&& ds.Tables.Count>0)
                 keywords =GetTuKhoaDTO(ds);
            
            if (!string.IsNullOrEmpty(filter) && filter != "*")
            {
                keywords.RemoveAll(k => !k.Keyword.ToLower().StartsWith(filter.ToLower()));
            }

            if (!string.IsNullOrEmpty(sort))
            {
                keywords.Sort(delegate(TuKhoaDTO x, TuKhoaDTO y)
                {
                    object a;
                    object b;

                    int direction = dir == "DESC" ? -1 : 1;

                    a = x.GetType().GetProperty(sort).GetValue(x, null);
                    b = y.GetType().GetProperty(sort).GetValue(y, null);

                    return System.Collections.CaseInsensitiveComparer.Default.Compare(a, b) * direction;
                });
            }

            if ((start + limit) > keywords.Count)
            {
                limit = keywords.Count - start;
            }

            List<TuKhoaDTO> rangePlants = (start < 0 || limit < 0) ? keywords : keywords.GetRange(start, limit);

            return new Ext.Net.Paging<TuKhoaDTO>(rangePlants, keywords.Count);
        }

        private static List<TuKhoaDTO>  GetTuKhoaDTO(DataSet dSet)
        {
            List<TuKhoaDTO> dsTuKhoa = new List<TuKhoaDTO>();
            if (dSet.Tables.Count != 0)
            {
                if (dSet.Tables[0].Rows.Count > 0)
                {

                    foreach (DataRow item in dSet.Tables["AllKeyword"].Rows)
                    {
                        TuKhoaDTO o = new TuKhoaDTO();
                        o.Keyword = item["keyword"].ToString();
                        dsTuKhoa.Add(o);
                    }
                }
            }
            return dsTuKhoa;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
